﻿using AJWPFAdmin.Core;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using DocumentFormat.OpenXml.Spreadsheet;
using Masuit.Tools.Security;
using MaterialDesignExtensions.Controls;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AJWPFAdmin.Services
{
    public class SystemUserService
    {
        private DbService db;
        private AJConfigService _ajConfigService;
        private bool _databaseCreated = false;

        public SystemUser CurrentUser { get; private set; }

        private Dictionary<string, string[]> _cachedColumnsConfig;
        public Dictionary<string, string[]> CachedColumnsConfig
        {
            get => _cachedColumnsConfig;
            private set => _cachedColumnsConfig = value;
        }

        public SystemUserService(AJConfigService agCfgSvc, DbService dbIns)
        {
            db = dbIns;
            _ajConfigService = agCfgSvc;
        }

        private void CreateColumnConfig()
        {
            _cachedColumnsConfig = CommonUtil.TryGetJSONObject<Dictionary<string, string[]>>(CurrentUser.TableColumnsConfig) ?? new Dictionary<string, string[]>();
        }

        public void SaveColumnsConfig(string key, string[] value)
        {
            if (_cachedColumnsConfig != null)
            {
                if (_cachedColumnsConfig.Keys.Any(p => p == key))
                {
                    _cachedColumnsConfig[key] = value;
                }
                else
                {
                    _cachedColumnsConfig.Add(key, value);
                }
                var uid = CurrentUser.Id;
                var cfgStr = CommonUtil.AJSerializeObject(_cachedColumnsConfig);
                db.SystemUsers.Where(p => p.Id == uid)
                    .ExecuteUpdate(sp => sp.SetProperty(p => p.TableColumnsConfig, cfgStr));
            }
        }

        public void RefreshDb()
        {
            db.Database.SetConnectionString(_ajConfigService.Config.GetConnectionString("MYSQL"));
        }

        public void Login(string account, string password)
        {
            if (!_databaseCreated)
            {
                db.Database.Migrate();
                _databaseCreated = true;
            }

            password = password.AESEncrypt(Core.Properties.Resources.AESKey);

            CurrentUser = db.SystemUsers
                .Where(x => (x.AccountName == account || x.Phone == account)
                && x.Password == password).FirstOrDefault();

            if (CurrentUser == null)
            {
                ExceptionTool.FriendlyError("账号或密码错误", "登录失败", true);
            }

            if (!CurrentUser.Enable)
            {
                ExceptionTool.FriendlyError("账号已被禁用", "登录失败", true);
            }

            CreateColumnConfig();
        }
    }
}
